$(function () {

    var id = getParamsByUrl(location.href, "id");

    var count = 0;
    var size = null;
    var productId = 0;

   if(id){
    $.ajax({
        type: "get",
        url: "/product/queryProductDetail",
        data: {
            id: id,
        },
        success: function (res) {
            console.log(res);
            count = res.num;
            productId = res.id;

            var html = template("productTpl", res);
            $("#product-box").html(html);

            var gallery = mui('.mui-slider');
            gallery.slider();

        }
    });
   }

    $("#product-box").on("tap",".size span",function(){
        $(this).addClass("active").siblings('span').removeClass("active");
        size = $(this).html();
    });

    var oInp = $("#inp");

    $("#increase").on("tap",function(){

        var num = oInp.val();
        num++;
        if(num > count){
            num = count;
        }
        oInp.val(num);

    });

    $("#reduce").on("tap",function(){

        var num = oInp.val();
        num--;
        if(num < 1){
            num = 1;
        }
        oInp.val(num);
    });

    $("#addCart").on("tap",function(){
        if(!size){
            mui.toast("请选择尺码");
            return;
        }

        $.ajax({
            type: "post",
            url: "/cart/addCart",
            data: {
                productId : productId,
                num : count,
                size : size 
            },
            success: function (res) {
               if(res.success){
                   
                mui.confirm("加入购物车成功，跳转到购物车？",function(mes){
                    if(mes.index == 1){
                        location.href = "cart.html";
                    }
                });

               }else {
                   mui.toast("添加购物车失败");
               }
                
            }
        });
    });

});